<?php

class FriendRequest extends ActiveRecordBase
{
	public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

	public function tableName() {
		return "{{friend_requests}}";
	}

	public function relations() {
		return array(
			'from' => array(self::HAS_ONE, 'User', array('user_id' => 'from_user_id')),
			'to' => array(self::HAS_ONE, 'User', array('user_id' => 'to_user_id')),
		);
	}

	public function rules()
	{
	}

	public function beforeSave() {
		if ( parent::beforeSave() && empty($this->timestamp) ) {
			$this->timestamp = parseDate($this->timestamp);
		}

		return true;
	}
	
	public static function sendRequest($user_id, $friend_id) {
		
		$command = app()->db->createCommand("REPLACE INTO {{friend_requests}} (from_user_id, to_user_id, timestamp) VALUES (:from_user_id, :to_user_id, :timestamp)");
		$result = $command->execute(array(
			':from_user_id' => $user_id,
			':to_user_id' => $friend_id,
			':timestamp' => time(),
		));
		
		return $result;
	}
	
	public static function sentRequest($user_id, $friend_id) {
		
		$model = FriendRequest::model()->findByAttributes(array(
			'from_user_id' => $user_id,
			'to_user_id' => $friend_id,
		), array(
			'order' => 't.timestamp ASC',
		));
		
		return !empty($model) ? true : false;
	}
	
	public static function removeRequest($user_id, $friend_id) {
		
		$model = FriendRequest::model()->findByAttributes(array(
			'from_user_id' => $user_id,
			'to_user_id' => $friend_id,
		));
		
		if ( $model ) $model->delete();
		
	}
}